package com.example.mcdonaldapplication.info

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.mcdonaldapplication.R
import com.example.mcdonaldapplication.activity.GoodsDetailActivity

class CartAdapter(private val cartList: ArrayList<CartInfo>, private val context: Activity) : RecyclerView.Adapter<CartAdapter.ViewHolder>(){

    class ViewHolder(view: View): RecyclerView.ViewHolder(view){
        val tvCartName: TextView = view.findViewById(R.id.tvCartName)
        val tvCartPrice: TextView = view.findViewById(R.id.tvCartPrice)
        val ivCartImg: ImageView = view.findViewById(R.id.ivCartImg)
        val tvCartNum: TextView = view.findViewById(R.id.tvCartNum)
        val btnInc:Button = view.findViewById(R.id.btnCartInc)
        val btnDec:Button = view.findViewById(R.id.btnCartDec)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.goods_cart,parent,false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val goodsInfo = cartList[position]
        holder.tvCartName.text = goodsInfo.name
        holder.tvCartPrice.text = goodsInfo.price
        if (goodsInfo.img == "0"){
            holder.ivCartImg.setImageResource(R.drawable.hamburger0)
        } else if (goodsInfo.img == "1"){
            holder.ivCartImg.setImageResource(R.drawable.hamburger1)
        }
        holder.tvCartNum.text = goodsInfo.num.toString()
        holder.btnDec.setOnClickListener{
            if(goodsInfo.num > 1){
                goodsInfo.num -= 1
                holder.tvCartNum.text = goodsInfo.num.toString()
                val editor = context.getSharedPreferences("cart", Context.MODE_PRIVATE).edit()
                editor.putInt("${goodsInfo.name}num", goodsInfo.num)
                editor.apply()
            }
        }
        holder.btnInc.setOnClickListener{
            goodsInfo.num += 1
            holder.tvCartNum.text = goodsInfo.num.toString()
            val editor = context.getSharedPreferences("cart", Context.MODE_PRIVATE).edit()
            editor.putInt("${goodsInfo.name}num", goodsInfo.num)
            editor.apply()
        }
    }

    override fun getItemCount(): Int {
        return cartList.size
    }
}